#!/usr/bin/env python
# coding: utf-8
"""
python system_mac_config.py --set "enable" --check "enable"    #query all mac, log unexpexted mac, and set system mac with inventory mac.
python system_mac_config.py --set "enable" --check "disable"   #query all mac, and set system mac with inventory mac.
python system_mac_config.py --set "disable" --check "enable"   #query all mac, and log unexpected mac.
python system_mac_config.py --set "disable" --check "disable"  #query all mac.
"""

import re
import os
import time
import datetime
import string
from onshs.ne.tnxxx.tnxxxcfg_basecase import *

log_node_prefix = "query_pos_ifindex"
log_node_summary = log_node_prefix+r"_summary"
log_node_fail = log_node_prefix+r"_fail"
log_node_success = log_node_prefix+r"_success"
log_node_warning = log_node_prefix+r"_warning"

log_file_notexisted_fail = "the file:%s isn't existed\n"
log_connect_fail = "connect ip:%s failed\n"

log_hsl_fail    = "ip:%s happened SBB00000649\n"
log_ifshow_fail = "ip:%s happened SBB00000681\n"

log_summary_success = "ip:%s doesn't happen SBB00000649/SBB00000681"
log_summary_fail = "ip:%s happens SBB00000649/SBB00000681"


class TestCase(TnxxxCfg_BaseCase):
    """
    TestCase
    """
    OPTIONS = [
        {
            'opt' : '--cfgfile',
            'dest': 'cfgfile',
            'metavar' : 'CFGFILE',
            'help' : 'the file of ip list configuration',
            'required' : False,
            'default' : "ip.txt"
        },       
    ]     
    
    def info_init(self):
        self.info_dic = {}     
              
        return True 
    
    #以node为关键字，把信息保存到info_dic[node]中。
    def info_show(self, node, info):        
        if not self.info_dic.has_key(node):
            self.info_dic[node] = ""
        self.info_dic[node] += info + '\n'        
        return True    
            
    def info_file_save(self, ip):
        path = os.getcwd()+'//'
        
        for node in self.info_dic:
            info_list = open(path+node+'_'+self.worktime+'.txt','a')            
            info_list.write(self.info_dic[node])
            info_list.close()
            
        return True
    
    def get_iplist(self):
        iplist_filted = []                
        if os.path.isfile(os.getcwd()+r'/'+ self.iplistfile):
            iplist = open(os.getcwd()+r'/'+ self.iplistfile)            
        else:
            self.info_show(log_node_fail, log_file_notexisted_fail%(self.iplistfile))            
            return iplist_filted 
        
        for line in iplist:
            if re.match(r'^\s*$', line) is not None : continue # 忽略空白行
            if re.match(r'^\s*#', line) is not None : continue # 忽略注释行            
            iplist_filted.append(line.strip('\n'))        
            
        iplist.close()
        
        return iplist_filted
        
     
    def get_based_iflist(self):
        query_cmd = r"show interface pos"
        rtn_str = None
        iflist = []
        rtn_str = self.tnxxx.send_rtn_str(query_cmd, self.get_ne_ip(0), 0, CLI_PORT)
        iflist = re.findall(r"IfName: (pos\d+.\d+).+\r\n.+(?:\n.+)?IfType: POS\(L2\)", rtn_str)        
        
        if_index_list = []
        for if_item in iflist:
            query_cmd = r"show interface %s" %(if_item)
            rtn_str = None       
            rtn_str = self.tnxxx.send_rtn_str(query_cmd, self.get_ne_ip(0), 0, ZEBOS_PORT)
            iflist = []
            #iflist = [('6.1', '5'), ('8.1', '6')]
            iflist = re.findall(r"Interface pos(\d+.\d+)\r\n.+\r\n.+index (\d+)", rtn_str)
            if len(iflist) > 0:
                if_index_list.append(iflist[0])
                print "%s %s\n" %(iflist[0][0],iflist[0][1])
                
        return if_index_list
    
    def get_hsl_iflist(self):        
        query_cmd = r"PSP_LgSwSrv_IfMgr_dump_if 0 ,-1"
            
        rtn_str = None       
        rtn_str = self.tnxxx.send_rtn_str(query_cmd, self.get_ne_ip(0), 0, DEV_PORT)
        hsl_iflist = re.findall(r"Interface pos(\d+.\d+) index (\w+)\r\n.+iftype 2", rtn_str)
        if len(hsl_iflist) != len(self.iflist):
            self.info_show(log_node_fail, log_hsl_fail%(self.get_ne_ip(0)))
            self.info_show(log_node_summary, log_summary_fail%(self.get_ne_ip(0)))
            return False
        else:
            for based_if in self.iflist:
                for hsl_if in hsl_iflist:
                    if based_if[0] == hsl_if[0] and int(based_if[1]) == int(hsl_if[1]):
                        break
                else:
                    self.info_show(log_node_fail, log_hsl_fail%(self.get_ne_ip(0)))
                    self.info_show(log_node_summary, log_summary_fail%(self.get_ne_ip(0)))
                    return False
                    
        return True
            
    def get_show_iflist(self):        
        query_cmd = '''ifShow "pos"'''
        rtn_str = None       
        rtn_str = self.tnxxx.send_rtn_str(query_cmd, self.get_ne_ip(0), 0, DEV_PORT)
        show_iflist = re.findall(r"unit number (\d+)", rtn_str)
        if len(show_iflist) != len(self.iflist):
            self.info_show(log_node_fail, log_ifshow_fail%(self.get_ne_ip(0)))
            self.info_show(log_node_summary, log_summary_fail%(self.get_ne_ip(0)))
            return False
        else:
            for based_if in self.iflist:
                for show_if in show_iflist:
                    if (int(based_if[0][0])-1)*256+int(based_if[0][2]) == int(show_if):
                        break
                else:
                    self.info_show(log_node_fail, log_ifshow_fail%(self.get_ne_ip(0)))
                    self.info_show(log_node_summary, log_summary_fail%(self.get_ne_ip(0)))
                    return False
        
        return True
            
    def _execute(self):                        
        self.info_init()
        
        worktime = str(datetime.datetime.now())
        self.worktime = worktime[:4]+worktime[5:7]+worktime[8:10]+'_'+worktime[11:13]+worktime[14:16]+worktime[17:19]
        
        self.iplistfile = self.options.cfgfile        
        self.work_path = os.getcwd()
        
        ip_list = self.get_iplist()         
        
        for ip in ip_list:            
            self.set_ne_ip(0, ip)              
            self.tnxxx.disconnect()   
            
            self.iflist = self.get_based_iflist() 
            if False == self.get_hsl_iflist():
                continue
            if False == self.get_show_iflist():
                continue
                            
            self.info_show(log_node_summary, log_summary_success%(ip))              
           
        worktime = str(datetime.datetime.now())
        self.worktime_end = worktime[:4]+worktime[5:7]+worktime[8:10]+'_'+worktime[11:13]+worktime[14:16]+worktime[17:19]
        
        self.info_show(log_node_summary, "The operation begin time %s "%(self.worktime))
        self.info_show(log_node_summary, "The operation end time %s "%(self.worktime_end))
        
        ip = '0.0.0.0'
        self.info_file_save(ip) 
        return True
    
if __name__ == "__main__" :
    case = TestCase()
    case.execute()